package main

import (
	"flag"
	"log"

	"nggs/debug"
	"nggs/util"

	protocol "nggs/network/protocol/protobuf/v3"
	link "nggs/network/tcp/v3"
	"nggs/network/tcp/v3/benchmark/msg"
)

var (
	flagAddr  = flag.String("a", ":8080", "listen addr, default=:8080")
	flagPprof = flag.String("p", ":8081", "pprof addr, default=:8081")
)

func main() {
	flag.Parse()

	pprofAddr, err := debug.StartPprofServer2(*flagPprof)
	if err != nil {
		log.Panicf("start pprof server %s fail", *flagPprof)
		return
	}
	log.Printf("start pprof server at %s", pprofAddr)

	server, err := link.Listen(*flagAddr, msg.Protocol, 0 /* sync send */, link.HandlerFunc(serverSessionLoop))
	checkErr(err)
	addr := server.Listener().Addr().String()
	go server.Serve()
	log.Printf("start server at %s", addr)
	util.WaitExitSignal()
}

func serverSessionLoop(session *link.Session) {
	ch := make(chan protocol.IMessage)

	go func() {
	loop:
		for {
			select {
			case iMsg := <-ch:
				switch iMsg.Head().MessageID {
				case msg.C2S_Ping_MessageID():
					recv := iMsg.(*msg.C2S_Ping)
					send := msg.New_S2C_Pong()
					send.Content = recv.GetContent()
					err := session.Send(send, 0)
					if err != nil {
						log.Println(err)
						break loop
					}
					//log.Printf("server send: %v", send)
				}
			}
		}
		session.Close()
	}()

	for {
		recv, _, err := session.Receive()
		if err != nil {
			log.Println(err)
			break
		}
		//log.Printf("server recv: %v", recv)
		ch <- recv.(protocol.IMessage)
	}

	session.Close()
}

func checkErr(err error) {
	if err != nil {
		log.Fatal(err)
	}
}
